package paper.parse;

import paper.token.TT;

import paper.parse.HMMatch;
import paper.parse.TokenInputStream;

import java.util.LinkedList;
import java.util.Iterator;

public class HMMatcher {
    private LinkedList<HMMatch> all = new LinkedList<HMMatch>();
    private HMMatch start;

    public HMMatcher() {
    }

    protected HMMatch addState() {
        HMMatch n = new HMMatch();
        if (start == null) {
            start = n;
        }
        all.add(n);
        return n;
    }

    private void reset() {
//        String x = "";
        for (Iterator<HMMatch> i = all.iterator(); i.hasNext(); ) {
            HMMatch m = i.next();
//            x = x + m.toString() + "\n";
            m.cache = null;
        }
//        System.out.println(x);
    }

    public void compile(String in) {
        all.clear();
        start = addState();
        HMMatch last = start;
        for (int i = 0; i < in.length(); i+=2) {
            TT match = TT.fromChar(in.charAt(i));
            TT out   = TT.fromChar(in.charAt(i+1));
            HMMatch s = addState();
            last.addOut(match, out, s);
            s.addOut(match, out, s);
            last = s;
        }
    }

    public void compile(MatchBuilder in) {
        all.clear();
        start = addState();
        HMMatch last = start;
        for (Iterator<MatchElement> i = in.iterator(); i.hasNext();) {
            MatchElement me = i.next();
            HMMatch s = addState();
            last.addOut(me.match, me.out, s);
            s.addOut(me.match, me.out, s);
            last = s;
        }
    }

    public Parse parse(TokenInputStream ts) {
        Parse pt = start.parse(ts);
        reset();
        return pt;
    }
}
